package kr.saeildamil.androidstudy_second33;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class PlayAudio extends Activity {
	ArrayList<String>mList;
	int mIdx;
	MediaPlayer mPlayer;
	Button mPlayBtn;
	TextView mFileName;
	SeekBar mProgress;
	boolean wasPlaying;
	String mSdPath;

	MediaRecorder mRecorder;
	Button mRecordStart;
	Button mRecordPlay;
	boolean mRecordstate;
	String mRecPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch33_playaudio);

		mList=new ArrayList<String>();
		mPlayer=new MediaPlayer();

		String ext=Environment.getExternalStorageState();
		if(!ext.equalsIgnoreCase(Environment.MEDIA_MOUNTED)){
			Toast.makeText(this, "SD 카드가 필요합니다", 0).show();
			finish();
			return;
		}

		mSdPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music";
		File sdRoot=new File(mSdPath);
		FilenameFilter filter=new FilenameFilter() {

			@Override
			public boolean accept(File dir, String filename) {
				return filename.endsWith(".mp3");
			}
		};

		String[] mpList=sdRoot.list(filter);
		if(mpList.length==0){
			Toast.makeText(this, "재생할 파일이 없음", 0).show();
			finish();
			return;
		}
		for(String str:mpList){
			Toast.makeText(this, mSdPath+"/"+str, 0).show();
			mList.add(mSdPath+"/"+str);
		}

		mFileName=(TextView) findViewById(R.id.filename);
		mPlayBtn=(Button) findViewById(R.id.play);
		mProgress=(SeekBar) findViewById(R.id.progress);

		mPlayer.setOnCompletionListener(mOnComplete);
		mPlayer.setOnSeekCompleteListener(mOnSeekComplete);
		mPlayer.setOnErrorListener(mOnError);
		mProgress.setOnSeekBarChangeListener(mOnSeek);
		mProgressHandler.sendEmptyMessageDelayed(0, 200);

		if(!loadMedia(mIdx)){
			Toast.makeText(this, "파일을 읽을 수 없음", 0).show();
			finish();
		}
		mIdx=0;

		/*mRecordStart=(Button) findViewById(R.id.ch33_recaudio_start);
		mRecordPlay=(Button) findViewById(R.id.ch33_recaudio_play);

		mRecordStart.setOnClickListener(mOnRecordStart);
		mRecordPlay.setOnClickListener(mOnRecorePlay);*/

	}
	/*OnClickListener mOnRecordStart=new OnClickListener() {

		@Override
		public void onClick(View v) {
			if(!mRecordstate){
				mRecPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/recaudio.3gp";
				if(mRecorder==null){
					mRecorder=new MediaRecorder();
				}else{
					mRecorder.reset();
				}

				mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
				mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
				mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
				mRecorder.setOutputFile(mRecPath);

				try {
					mRecorder.prepare();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mRecorder.start();
				mRecordstate=true;
				mRecordStart.setText("Stop");
			}else{
				mRecorder.stop();
				mRecorder.release();
				mRecorder=null;
				mRecordstate=false;
				mRecordStart.setText("Start");
			}
		}
	};

	OnClickListener mOnRecorePlay=new OnClickListener() {

		@Override
		public void onClick(View v) {
			if(mRecPath.length()==0 || mRecordstate){
				Toast.makeText(PlayAudio.this, "녹음을 먼저 하세요", 0).show();
				return;
			}
			MediaPlayer player=new MediaPlayer();
			try {
				player.setDataSource(mRecPath);
				player.prepare();
				player.start();
			} catch (Exception e) {
				Toast.makeText(PlayAudio.this, "error : "+e.getMessage(), 0).show();
			}

		}
	};
*/
	public void mOnClick(View v){
		switch (v.getId()) {
		case R.id.play:
			if(!mPlayer.isPlaying()){
				mPlayer.start();
				mPlayBtn.setText("Pause");
			}else{
				mPlayer.pause();
				mPlayBtn.setText("Play");
			}
			break;
		case R.id.stop:
			mPlayer.stop();
			mPlayBtn.setText("Stop");
			mProgress.setProgress(0);
			try {
				mPlayer.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		case R.id.prev:
			break;
		case R.id.next:
			wasPlaying=mPlayer.isPlaying();

			if(v.getId()==R.id.prev){
				mIdx=(mIdx==0?mList.size()-1:mIdx-1);
			}else{
				mIdx=(mIdx==mList.size()-1?0:mIdx+1);
			}
			break;
		}
	}

	MediaPlayer.OnErrorListener mOnError=new OnErrorListener() {

		@Override
		public boolean onError(MediaPlayer mp, int what, int extra) {
			String err="OnError occoured. what="+what+",extra"+extra;
			Toast.makeText(PlayAudio.this, err, 0).show();
			return false;
		}
	};

	OnSeekBarChangeListener mOnSeek=new OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
		}
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			wasPlaying=mPlayer.isPlaying();
			if(wasPlaying){
				mPlayer.pause();
			}
		}
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if(fromUser){
				mPlayer.seekTo(progress);
			}
		}
	};

	// 재생 위치 이동
	OnSeekCompleteListener mOnSeekComplete=new OnSeekCompleteListener() {

		@Override
		public void onSeekComplete(MediaPlayer mp) {
			if(wasPlaying){
				mPlayer.start();
			}
		}
	};

	//재생 완료 되면 다음곡으로
	OnCompletionListener mOnComplete=new OnCompletionListener() {

		@Override
		public void onCompletion(MediaPlayer mp) {
			//전곡이 다 재생되면 첫곡으로 그렇지 않으면 다음곡으로
			mIdx=(mIdx==mList.size()-1?0:mIdx+1);
			mPlayer.reset();
			loadMedia(mIdx);
			mPlayer.start();
		}
	};

	//항상 준비 상태여야 한다
	boolean loadMedia(int mIdx){
		try {
			mPlayer.setDataSource(mList.get(mIdx));
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mFileName.setText("파일 : "+mList.get(mIdx));
		mProgress.setMax(mPlayer.getDuration());
		return true;
	}

	//0.2초에 한 번꼴로 재생 위치 갱싱
	Handler mProgressHandler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(mPlayer==null)return;
			if(mPlayer.isPlaying()){
				mProgress.setProgress(mPlayer.getCurrentPosition());
			}
			mProgressHandler.sendEmptyMessageDelayed(0, 200);
		}
	};
}
